<?php

namespace mpend\modules\user\models;

use Yii;
use yii\db\Exception;
use mpend\models\User;
use common\models\user\UserMeta;

/**
 * 个人信息修改模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class ProfileForm extends \common\base\Model {

    /**
     * @var integer 用户UID
     */
    public $id;

    /**
     * @var string 头像
     */
    public $avatar;

    /**
     * @var string 昵称
     */
    public $nickname;

    /**
     * @var integer 性别
     */
    public $gender = 0;

    /**
     * @var date 出生日期
     */
    public $birthday;

    /**
     * @var string 邮箱
     */
    public $email;

    /**
     * @var string 位置
     */
    public $location;

    /**
     * @var User|null 用户信息
     */
    private $_user = null;

    /**
     * @var UserMeta|null 用户信息
     */
    private $_userMeta = null;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['id', 'gender'], 'integer'],
            ['avatar', 'string', 'max' => 255],
            [['nickname'], 'string', 'max' => 30],
            ['gender', 'in', 'range' => [0, 1, 2]],
            ['birthday', 'date', 'format' => 'yyyy-MM-dd'],
            [['location', 'email'], 'string', 'max' => 50],
            [['id'], 'validateUser'],
            [['nickname'], 'validateNickname'],
        ];
    }

    public function validateUser($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $user = User::findOne($this->$attribute);
        if (!$user) {
            return $this->addError($attribute, '用户信息未找到！');
        }
        $meta = $user->meta;
        if (!$meta) {
            $meta = new UserMeta();
            $meta->id = $user->id;
        }
        $this->_user = $user;
        $this->_userMeta = $meta;
    }

    public function validateNickname($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $nickname = $this->$attribute;
        if (!$nickname) {
            return;
        }
        $nicknameDuplication = User::find()->andWhere([
            'and',
            ['!=', 'id', $this->id],
            ['nickname' => $nickname],
        ])->exists();
        if ($nicknameDuplication) {
            return $this->addError($attribute, '昵称已被占用，请更换昵称！');
        }
    }

    /**
     * @return User
     */
    public function getUser() {
        return $this->_user;
    }

    /**
     * @return UserMeta
     */
    public function getUserMeta() {
        return $this->_userMeta;
    }

    /**
     * @return User
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('');
        }
        $user = $this->getUser();
        $meta = $this->getUserMeta();
        //用户账户信息
        if ($this->email) {
            $user->email = $this->email;
        }
        if ($this->avatar) {
            $user->avatar = $this->avatar;
        }
        if ($this->nickname) {
            $user->nickname = $this->nickname;
        }
        //用户扩展信息
        if ($this->gender) {
            $meta->gender = $this->gender;
        }
        if ($this->birthday) {
            $meta->birthday = $this->birthday;
        }
        if ($this->location) {
            $meta->location = $this->location;
        }

        //开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$user->save()) {
                throw new Exception($user->getErrorMsg());
            }
            if (!$meta->save()) {
                throw new Exception($meta->getErrorMsg());
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            return $this->dumpError($e->getMessage());
        }
        return $user;
    }

}
